<?php

namespace App\Admin\Controllers;

use Encore\Admin\Grid;
use App\Models\VipPurchase;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\VipPurchase\VipPurchaseCancel;

class VipPurchasesController extends AdminController
{
    protected $title = '会员付费记录';

    protected function grid()
    {
        $grid = new Grid(new VipPurchase());
        $grid->model()->orderByDesc('id');
	
	    if ($userId = request('user_id')) {
		    $grid->model()->where('user_id', $userId)->orderByDesc('id');
	    }

        $grid->column('id', 'ID');
	    $grid->column('user_id', '会员')->display(function () {
		    return $this->user ? $this->user->nameText(true) : '';
	    });
        $grid->column('number', '单号');
        $grid->column('total_amount', '金额');
	    $grid->column('created_at', '下单时间')->display(function () {
		    return (string)$this->created_at;
	    });
	    $grid->column('paid_at', '付款时间')->display(function () {
		    return $this->paid_at ? (string)$this->paid_at : '待付款...';
	    });
	    $grid->column('paid_method', '付款方式')->display(function ($value) {
		    if (empty($value)) {return "<i class='fa fa-times-circle text-default'></i> 未支付";}
		    $method = config("site.payment.methods.{$value}");
		    $method = empty($method) ? $value : $method;
		    $text = "<i class='fa fa-check-circle text-success'></i> {$method}";
		    return $text;
	    });
	    $grid->column('cancelled_at', '取消状态')->display(function ($value) {
	    	if ($this->paid_at and !$value) {
			    return _label('状态正常', 'success');
		    }
	    	if ($this->paid_at and $value) {
	    		return _label('已经取消', 'danger');
		    }
	    	return _label('等待付款', 'default');
	    });
		$grid->column('is_new', '是否新会员')->display(function () {
		 	return $this->is_new ? _true() : _false() ;
		});
	    $this->gridFilter($grid);
	
	    $grid->disableRowSelector();
	    $grid->disableCreateButton();
	    $grid->disableExport();
	    $this->gridActions($grid);

        return $grid;
    }
    
	protected function gridFilter(Grid $grid)
	{
		$grid->filter(function (Grid\Filter $filter) {
			$filter->expand();
			$filter->column(1/2, function (Grid\Filter $filter) {
				$filter->disableIdFilter();
				$filter->equal('user_id', '会员 ID 查询');
			});

			$filter->column(1/2, function (Grid\Filter $filter) {
				$filter->disableIdFilter();
				$filter->equal('number', '单号查询');
			});
		});
	}
	
	protected function gridActions(Grid $grid)
	{
		$grid->actions(function (Grid\Displayers\Actions $actions) {
			$actions->disableEdit();
			$actions->disableView();
			$actions->disableDelete();
			$actions->add(new VipPurchaseCancel());
		});
	}
}
